﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.Extensions.DependencyInjection;
using Infrastructure.Data;
using System;
using Microsoft.Extensions.Logging;
using Infrastructure.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace Web
{
	public class Program
	{
		public static void Main(string[] args)
		{


			var host = BuildWebHost(args);

			using (var scope = host.Services.CreateScope())
			{
				var services = scope.ServiceProvider;
				var loggerFactory = services.GetRequiredService<ILoggerFactory>();
				try
				{
					var ZBContext = services.GetRequiredService<ZBContext>();

					CheckMigrations(ZBContext);

					ZBContextSeed.SeedAsync(ZBContext, loggerFactory)
			.Wait();

					var appIdentityDbContext = services.GetRequiredService<AppIdentityDbContext>();
					//默认建立后台管理员 和 角色（管理员，代理商、会员、游客）
					var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
					var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
					AppIdentityDbContextSeed.SeedAsync(userManager, roleManager, appIdentityDbContext).Wait();


				}
				catch (Exception ex)
				{
					var logger = loggerFactory.CreateLogger<Program>();
					logger.LogError(ex, "An error occurred seeding the DB.");
				}
			}

			host.Run();
		}

		public static IWebHost BuildWebHost(string[] args) =>
			WebHost.CreateDefaultBuilder(args)
				.UseStartup<Startup>()
				.Build();

		/// <summary>
		/// 检查迁移
		/// </summary>
		/// <param name="db"></param>
		static void CheckMigrations(DbContext db)
		{
			Console.WriteLine("Check Migrations");    //判断是否有待迁移
			if (db.Database.GetPendingMigrations().Any())
			{
				Console.WriteLine("Migrating...");        //执行迁移
				db.Database.Migrate();
				Console.WriteLine("Migrated");
			}
			Console.WriteLine("Check Migrations Coomplete!");
		}
	}
}
